# To change this template, choose Tools | Templates
# and open the template in the editor.

#imports
import urllib2
import json

node_name = ""
url = ""
node_values = ""
values = ""
descriptors = []
descriptors_values = {}


#valid params
def valid_param(params):
    if 'name' in params:
        global node_name
        node_name = params['name']
    else:
        raise Exception("Name is not defined")

    if 'url' in params:
        global url
        url = str(params['url'])
    else:
        raise Exception("Url is not defined")

    if 'node_values' in params:
        global node_values
        node_values = str(params['node_values'])


#get json file an convert to object/array
def get_json_url(url):
    req = urllib2.Request(url)
    opener = urllib2.build_opener()
    f = opener.open(req)
    data_json = json.load(f)
    try:
        global values
        values = data_json[node_values]
        return True
    except Exception:
        return False

#set the descriptors values
def set_descriptors_values(values):
    global descriptors
    global descriptors_values
    for val in values:
        if is_interable(val):            
            for _val in values[val]:
                name = val+"_"+_val
                tempDesc = {'name': name,
                        'call_back': get_descriptors_values,
                        'time_max': 10,
                        'value_type': 'float',
                        'units': 'req/sec',
                        'slope': 'both',
                        'format': "%.3f",
                        'description': "Description" + _val,
                        'groups': "root,"+ val}
                descriptors_values[name] = values[val][_val]
                descriptors.append(tempDesc)                                
        else:
            tempDesc = {'name': val,
                        'call_back': get_descriptors_values,
                        'time_max': 90,
                        'value_type': 'float',
                        'units': 'req/sec',
                        'slope': 'both',
                        'format': "%.3f",
                        'description': "Description" + val,
                        'groups': "root"}
            
            descriptors_values[val] = values[val]
            descriptors.append(tempDesc)
    return descriptors
           
#valid interable
def is_interable(val):
    try:
        for temp in values[val]:
            return True
    except Exception:
        return False
    
#get the descriptors values
def get_descriptors_values(name):        
    return descriptors_values[name]

    
#init te module
def metric_init(params):    
    valid_param(params)
    if get_json_url(url) :        
        return set_descriptors_values(values)
    else :
        raise Exception("Value no exist in the json")

def metric_cleanup():
    pass